<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0,user-scalable=no,minimal-ui">
    <title>博川</title>
    <link rel="icon" href="./../images/favico.ico">
    <!--不同屏幕尺寸根字体设置-->
    <script src="./../js/base.js"></script>
    <!--element-ui的样式-->
    <link rel="stylesheet" href="../../backend/plugins/element-ui/index.css" />
    <!-- 引入样式  -->
    <link rel="stylesheet" href="../styles/index.css" />
    <!--引入vant样式-->
    <link rel="stylesheet" href="../styles/vant.min.css"/>
    <!--本页面内容的样式-->
    <link rel="stylesheet" href="./../styles/order.css" />
</head>
<body>
<div id="order" class="app">
    <div class="divHead">
        <div class="divTitle">
            <i class="el-icon-arrow-left" @click="goBack"></i>博川
        </div>
    </div>
    <div class="divBody" v-if="orderList.length > 0">
        <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="getList">
            <van-cell v-for="(order,index) in orderList" :key="index" class="item">
                <div class="timeStatus">
                    <span>{{order.orderTime}}</span>
                    <span>{{getStatus(order.status)}}</span>
                </div>
                <div class="dishList">
                    <div v-for="(item,index) in order.orderDetails" :key="index" class="item">
                        <span>{{item.name}}</span>
                        <span>x{{item.number}}</span>
                    </div>
                </div>
                <div class="result">
                    <span>共{{order.sumNum}} 件商品,实付</span><span class="price">￥{{order.amount}}</span>
                </div>
                <div class="btn" v-if="order.status === 4">
                    <div class="btnAgain" @click="addOrderAgain(order)">再来一单</div>
                </div>
            </van-cell>
        </van-list>
    </div>
    <div class="divNoData" v-else>
        <div class="divContainer">
            <img src="./../images/no_order.png"/>
            <div>暂无订单</div>
        </div>
    </div>
</div>
<!-- 开发环境版本，包含了有帮助的命令行警告 -->
<script src="../../backend/plugins/vue/vue.js"></script>
<!-- 引入组件库 -->
<script src="../../backend/plugins/element-ui/index.js"></script>
<!-- 引入vant组件 -->
<script src="./../js/vant.min.js"></script>
<!-- 引入axios -->
<script src="../../backend/plugins/axios/axios.min.js"></script>
<script src="./../js/request.js"></script>
<script src="./../api/order.js"></script>
<script>
    new Vue({
        el:"#order",
        data(){
            return {
                paging:{
                    page:1,
                    pageSize:5
                },
                orderList:[],
                loading:false,
                finished:false,
                form:{
                    phone:'',
                    code:''
                },
                msgFlag:false,
                userPhone: ''
            }
        },
        computed:{},
        created(){
            this.userPhone = sessionStorage.getItem("userPhone")
            this.initData()
        },
        mounted(){},
        methods:{
            goBack(){
                const url = document.referrer
                //表示是从订单页面跳转过来的
                if(url.includes('success')){
                    window.requestAnimationFrame(()=>{
                        window.location.href= '/front/index.html'
                    })
                }else{
                    history.go(-1)
                }
            },
            toAddressPage(){
                window.requestAnimationFrame(()=>{
                    window.location.href = '/front/page/address.html'
                })
            },
            initData(){
                console.log('order页面加载完成2')
                this.getList()
            },
            async getList(){
                if(this.finished){
                    this.loading = false;
                    return
                }
                const res = await orderPagingApi(this.paging)
                if(res.code === 1){
                    let records = res.data.records
                    if(records && Array.isArray(records)){
                        records.forEach(item=>{
                            console.log("处理订单:", item);
                            // 确保使用后端计算的sumNum字段
                            if(item.sumNum !== undefined && item.sumNum !== null) {
                                // 使用后端计算的值
                                item.sumNum = parseInt(item.sumNum) || 0;
                            } else {
                                // 如果后端没有正确计算sumNum，则按原有逻辑计算
                                let number = 0
                                if(item.orderDetails && Array.isArray(item.orderDetails)) {
                                    item.orderDetails.forEach(ele=>{
                                        number += parseInt(ele.number) || 0
                                    })
                                }
                                item.sumNum = number
                            }
                            console.log("订单ID: " + item.id + ", 最终sumNum: " + item.sumNum);
                        })
                        this.orderList.push(...records)
                    }
                    this.loading = false;
                    if(this.paging.page >= res.data.pages){
                        this.finished = true;
                    }
                    this.paging.page = this.paging.page + 1
                }else{
                    this.$notify({ type:'warning', message:res.msg});
                    this.loading = false;
                }
            },

            async addOrderAgain(order){
                if (!order || !order.id) {
                    return;
                }
                try {
                    const response = await axios.post('/order/again', {id: order.id});

                    if (response.data.code === 1) {
                        setTimeout(() => {
                            window.location.href = '/front/index.html';
                        }, 200);
                    }
                } catch (error) {
                    // 静默处理错误
                }
            },
            getStatus(status){
                let str = ''
                switch(status){
                    case 1:
                        str =  '待付款'
                        break;
                    case 2:
                        str =  '正在派送'
                        break;
                    case 3:
                        str =  '已派送'
                        break;
                    case 4:
                        str =  '已完成'
                        break;
                    case 5:
                        str =  '已取消'
                        break;
                }
                return str
            },
            // 添加确认收货方法
            async confirmDelivery() {
                if (!this.orderList || this.orderList.length === 0 || !this.orderList[0].id) {
                    this.$notify({ type:'warning', message: '订单信息不完整'});
                    return;
                }

                try {
                    const res = await updateOrderStatusApi({
                        id: this.orderList[0].id,
                        status: 3  // 3表示已派送
                    });

                    if(res.data.code === 1){
                        this.$notify({ type:'success', message: '确认收货成功'});
                        // 更新订单状态显示
                        this.orderList[0].status = 3;
                    } else {
                        this.$notify({ type:'warning', message: res.data.msg});
                    }
                } catch (error) {
                    this.$notify({ type:'danger', message: '确认收货失败'});
                    console.error('确认收货异常:', error);
                }
            },
            async toPageLogin(){
                const res = await loginoutApi()
                if(res.code === 1){
                    window.requestAnimationFrame(()=>{
                        window.location.href = '/front/page/login.html'
                    })
                }else{
                    this.$notify({ type:'warning', message:res.msg});
                }
            }
        }
    })
</script>
</body>
</html>